package com.jic.manager.controller.manage.conf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.base.vo.enums.DeptTypeEnums;
import com.jic.conf.request.CmsPageRequest;
import com.jic.conf.response.CmsModuleResponse;
import com.jic.conf.response.CmsPageResponse;
import com.jic.manager.common.util.BeanUtil;
import com.jic.manager.entity.CmsPage;
import com.jic.manager.entity.CmsPageType;
import com.jic.manager.enums.CmsPageStatusEnums;
import com.jic.manager.enums.CmsPageTypeEnums;
import com.jic.manager.enums.ResponseCode;
import com.jic.manager.exception.AppRuntimeException;
import com.jic.manager.service.CmsModuleService;
import com.jic.manager.service.CmsPageService;
import com.jic.manager.service.CmsPageTypeService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/cmsPage")
public class CmsPageController {

	@Autowired
	private CmsPageService cmsPageService;

	@Autowired
	private CmsPageTypeService cmsPageTypeService;
	
	@Autowired
	private CmsModuleService cmsModuleService;
	


	@ApiOperation(value = "分页查询", notes = "分页查询信息")
	@ResponseBody
	@RequestMapping(value = "cmsPagQquery", method = RequestMethod.POST)
	public RestResult<PageResult<CmsPageResponse>> queryPage(@RequestBody CmsPageRequest cmsPageRequest) {

		log.info("开始调用分页，{}", JSON.toJSONString(cmsPageRequest));

		Page page = new Page();
		page.setLimit(cmsPageRequest.getLimit());
		page.setStart(cmsPageRequest.getStart());

		CmsPage cmsPage = BeanUtil.copy(cmsPageRequest, CmsPage.class);
		cmsPage.setDeleteFlag(0);
		
		cmsPage.setUpdator(null);
		cmsPage.setCreator(null);
		if(cmsPage.getMerchantId()!=null && cmsPage.getMerchantId()==0) {
			cmsPage.setMerchantId(cmsPage.getMerchantId());
		}
		if(cmsPage.getStoreId()!=null && cmsPage.getStoreId()==0) {
			cmsPage.setStoreId(cmsPage.getStoreId());
		}
		cmsPage.setDeptIds(CollectionUtils.isEmpty(cmsPageRequest.getAdminOperate().getDeptIds()) ? null : cmsPageRequest.getAdminOperate().getDeptIds());

		if (cmsPage.getPageType() == null){
			cmsPage.setPageType(CmsPageTypeEnums.PLATFORM_HOME_PAGE.getType());
		}
		PageResult<CmsPage> pageRresult = cmsPageService.queryPages(cmsPage, page);

		List<CmsPageResponse> cmsPageResponseList = pageRresult.getRows().stream().map(temp -> {
			CmsPageResponse cmsPageResponse = BeanUtil.copy(temp, CmsPageResponse.class);
			return cmsPageResponse;
		}).filter(item -> item != null).collect(Collectors.toList());

		PageResult<CmsPageResponse> result = new PageResult<>();
		result.setRows(cmsPageResponseList);
		result.setTotal(pageRresult.getTotal());

		return RestResult.success(result);
	}

	@ResponseBody
	@ApiOperation(value = "页面类型查询", notes = "页面类型查询信息")
	@RequestMapping(value = "queryCmsPageType", method = RequestMethod.POST)
	public RestResult<List<CmsPageType>> queryCmsPageType() {

		List<CmsPageType> list = cmsPageTypeService.query(null);

		return RestResult.success(list);
	}

	/**
	 * 
	 * 
	 * @return
	 */
	@ResponseBody
	@ApiOperation(value = "页面删除", notes = "页面删除")
	@RequestMapping(value = "/deleteCmsPage")
	public RestResult deleteCmsPage(@RequestBody CmsPageRequest cmsPageRequest) {
		RestResult restResult = new RestResult<>();
		try {
			long flag = cmsPageService.delete(cmsPageRequest.getId());
			if (flag == 1) {
				restResult = RestResult.success(restResult);
			}
		} catch (Exception e) {
			log.error("页面删除异常",e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION);
		}
		return restResult;

	}

	/**
	 * 
	 * 
	 * @return
	 */
	@ResponseBody
	@ApiOperation(value = "发布页面", notes = "发布页面")
	@RequestMapping(value = "/pushCmsPage", method = RequestMethod.POST)
	public RestResult pushCmsPage(@RequestBody CmsPageRequest cmsPageRequest) {
		RestResult restResult = new RestResult<>();
		try {

			CmsPage cmsPage = new CmsPage();
			cmsPage.setId(cmsPageRequest.getId());
			cmsPage.setStatus(1);
			long flag = cmsPageService.update(cmsPage);
			if (flag == 1) {

				cmsPageService.lowerCmspage(cmsPageRequest.getId());

				restResult = RestResult.success(restResult);
			}
		} catch (Exception e) {
			log.error("发布页面",e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION);
		}
		return restResult;

	}

	/**
	 * 
	 * 
	 * @return
	 */
	@ResponseBody
	@ApiOperation(value = "下架页面", notes = "下架页面")
	@RequestMapping(value = "/lowerCmspage", method = RequestMethod.POST)
	public RestResult lowerCmspage(@RequestBody CmsPageRequest cmsPageRequest) {
		RestResult restResult = new RestResult<>();
		try {
			CmsPage cmsPage = new CmsPage();
			cmsPage.setId(cmsPageRequest.getId());
			long flag = cmsPageService.update(cmsPage);
			if (flag == 1) {
				restResult = RestResult.success(restResult);
			}
		} catch (Exception e) {
			log.error("下架页面",e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION);
		}
		return restResult;
	}

    /**
     *
     *
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "上架页面", notes = "上架页面")
    @RequestMapping(value = "/lowerSoldOut", method = RequestMethod.POST)
    public RestResult lowerSoldOut(@RequestBody CmsPageRequest cmsPageRequest) {
        RestResult restResult = new RestResult<>();
        try {
            CmsPage cmsPage = new CmsPage();
            cmsPage.setId(cmsPageRequest.getId());
            cmsPage.setStatus(1);
            long flag = cmsPageService.updateSoldOut(cmsPage);
            if (flag == 1 && cmsPageRequest.getPageType().equals(CmsPageTypeEnums.PLATFORM_HOME_PAGE.getType())) {
            	// 首页上架 将之前已上架的首页下架
				cmsPageService.lowerCmspage(cmsPageRequest.getId());
            }
			restResult = RestResult.success(restResult);
		} catch (Exception e) {
            log.error("上架页面",e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION);
        }
        return restResult;

    }

	/**
	 * 
	 * 普通页面复制功能
	 * 
	 * @return
	 */
	@ResponseBody
	@ApiOperation(value = "复制页面", notes = "复制页面")
	@RequestMapping(value = "/copyCmsPage", method = RequestMethod.POST)
	public RestResult copyCmsPage(@RequestBody CmsPageRequest cmsPageRequest) {
		RestResult restResult = new RestResult();
		try {

			// 根据Id查处所有关联的数据进行复制
			cmsPageService.copyCmsPage(cmsPageRequest.getId());

			restResult = RestResult.success(restResult);

		} catch (Exception e) {
			log.error("复制页面",e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION);
		}
		return restResult;

	}
	
	/**
	 * 
	 * 普通页面复制功能
	 * 
	 * @return
	 */
	@ResponseBody
	@ApiOperation(value = "使用模版", notes = "使用模版")
	@RequestMapping(value = "/useCmsTpage", method = RequestMethod.POST)
	public RestResult useCmsTpage(@RequestBody CmsPageRequest cmsPageRequest) {
		RestResult restResult = new RestResult();
		try {

			// 根据Id查处所有关联的数据进行复制
			Long id = cmsPageService.useCmsPage(cmsPageRequest.getId());

			restResult = RestResult.success(id);

		} catch (Exception e) {
			log.error("使用模版",e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION);
		}
		return restResult;

	}

	/**
	 * 
	 * 普通页面编辑功能
	 * 
	 * @param
	 * @return
	 */
	@ResponseBody
	@ApiOperation(value = "编辑页面", notes = "编辑页面")
	@RequestMapping(value = "/editCmsPage", method = RequestMethod.POST)
	public RestResult<CmsPageResponse> editCmsPage(@RequestBody CmsPageRequest cmsPageRequest) {
		
		try {
			CmsPageResponse cmsPageResponse = new CmsPageResponse();

			CmsPage cmsPage = cmsPageService.queryByPrimaryKey(cmsPageRequest.getId());

			Optional.ofNullable(cmsPage).orElseThrow(() -> new AppRuntimeException(ResponseCode.EXCEPTION, cmsPageRequest.getId()+",不存在"));
			
			cmsPageResponse.setId(cmsPageRequest.getId());
			cmsPageResponse.setTitle(cmsPage.getTitle());
			
//			CmsModule cmsModule = new CmsModule();
//			cmsModule.setCmsPageId(id);
//			// 普通页面
//			cmsModule.setRefType(0);
//			cmsModule.setDeleteFlag(0);
//			// 查询页面更下的所有栏目
//			List<CmsModule> cmsModules = cmsModuleService.query(cmsModule);
//			
//			if(CollectionUtils.isNotEmpty(cmsModules)) {
//				List<Long> cmsModelIds = new ArrayList<>();
//
//				for (CmsModule bean : cmsModules) {
//					cmsModelIds.add(bean.getId());
//				}
//				
//
//				Map<Long, List<CmsModuleData>> cmsModuleDataMap = new HashMap<>();
//
//				Map<Long, CmsModuleTemplate> cmsModuleTemplateMap = new HashMap<>();
//				List<CmsModuleTemplate> cmsModuleTemplates = cmsModuleTemplateService.queryByModuleIds(cmsModelIds);
//
//				if (CollectionUtils.isNotEmpty(cmsModuleTemplates)) {
//					// 因为是1对1关系，不需要判断直接放入map
//					for (CmsModuleTemplate entity : cmsModuleTemplates) {
//						cmsModuleTemplateMap.put(entity.getCmsModuleId(), entity);
//					}
//				}
//				
//				// 查询栏目下的所有
//				List<CmsModuleData> cmsModuleDatas = cmsModuleDataService.queryByModuleIds(cmsModelIds);
//
//				if (CollectionUtils.isNotEmpty(cmsModuleDatas)) {
//					for (CmsModuleData entity : cmsModuleDatas) {
//
//						List<CmsModuleData> lst = cmsModuleDataMap.get(entity.getCmsModuleId());
//						if (lst == null) {
//							lst = new ArrayList<>();
//							lst.add(entity);
//						} else {
//							lst.add(entity);
//						}
//
//						cmsModuleDataMap.put(entity.getCmsModuleId(), lst);
//					}
//				}
//
//				
//				
//				List<CmsModuleResponse> cmsModuleResponses = new ArrayList<> ();
//				CmsModuleResponse cmsModuleResponse = null;
//				CmsModuleDataResponse cmsModuleDataResponse = null;
//				for (CmsModule bean : cmsModules) {
//					cmsModuleResponse = new CmsModuleResponse();
//					cmsModuleResponse.setId(bean.getId());
//					cmsModuleResponse.setDataType(bean.getDataType());
//					cmsModuleResponse.setName(bean.getName());
//					cmsModuleResponse.setProductNums(bean.getProductNums());
//					cmsModuleResponse.setSort(bean.getSort());
//					
//					// 取得商品信息
//					List<CmsModuleData> lst = cmsModuleDataMap.get(bean.getId());
//					if(CollectionUtils.isNotEmpty(lst)) {
//						
//						List<CmsModuleDataResponse> cmsModuleDataResponses = new ArrayList<>();
//						
//						for(CmsModuleData entity :lst) {
//							cmsModuleDataResponse = new CmsModuleDataResponse();
//							cmsModuleDataResponse.setCmsModuleId(entity.getCmsModuleId());
//							cmsModuleDataResponse.setId(entity.getId());
//							cmsModuleDataResponse.setIsOffShelve(entity.getIsOffShelve());
//							cmsModuleDataResponse.setMpcode(entity.getMpcode());
//							cmsModuleDataResponse.setMpId(entity.getMpId());
//							cmsModuleDataResponse.setPromotionId(entity.getPromotionId());
//							cmsModuleDataResponse.setSortValue(entity.getSortValue());
//							cmsModuleDataResponses.add(cmsModuleDataResponse);
//						}
//						
//						cmsModuleResponse.setCmsModuleData(cmsModuleDataResponses);
//					}
//					
//					
//					
//					// 设置栏目模板信息
//					CmsModuleTemplate cmsModuleTemplate = cmsModuleTemplateMap.get(bean.getId());
//					
//					if(cmsModuleTemplate != null) {
//						
//						CmsModuleTemplateResponse cmsModuleTemplateResponse = new CmsModuleTemplateResponse();
//						cmsModuleTemplateResponse.setCmsModuleId(cmsModuleTemplate.getCmsModuleId());
//						cmsModuleTemplateResponse.setCmsTemplateId(cmsModuleTemplate.getCmsModuleId());
//						cmsModuleTemplateResponse.setCode(cmsModuleTemplate.getCode());
//						cmsModuleTemplateResponse.setId(cmsModuleTemplate.getId());
//						cmsModuleTemplateResponse.setName(cmsModuleTemplate.getName());
//						cmsModuleTemplateResponse.setPreviewImg(cmsModuleTemplate.getPreviewImg());
//						cmsModuleTemplateResponse.setVariables(cmsModuleTemplate.getVariables());
//						cmsModuleResponse.setCmsModuleTemplate(cmsModuleTemplateResponse);
//					}
//
//					
//					cmsModuleResponses.add(cmsModuleResponse);
//				}
				
			    List<CmsModuleResponse> cmsModuleResponses  = cmsModuleService.query(cmsPageRequest.getId(), 0);
				
				cmsPageResponse.setCmsModules(cmsModuleResponses);
			//}

			
			return RestResult.success(cmsPageResponse);

		} catch (Exception e) {
			log.error("编辑页面",e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION);
		}

		

	}




	/**
	 * CMS_PAGE 查询列表（分页）
	 * @param request 前端请求参数
	 */
	@PostMapping("/listPage")
	@ApiOperation(value = "分页查询cmsPage列表")
	@ResponseBody
	public RestResult<PageResult<CmsPageResponse>>  listCmsPageRecordPagination(@RequestBody com.jic.manager.entity.vo.request.CmsPageRequest request) throws Throwable {
		//分页处理
		PageResult<CmsPageResponse> pageResult = new PageResult<>();
		CmsPage cmsPage = new CmsPage();
		try {
			BeanUtils.copyProperties(request, cmsPage);
			List<com.jic.manager.entity.vo.response.CmsPageResponse> list = cmsPageService.listCmsPageRecordPagination(request);
			long count = cmsPageService.listPageCount(cmsPage);
			List<CmsPageResponse> responseList = list.stream().map(temp -> {
				CmsPageResponse bo = new CmsPageResponse();
				BeanUtils.copyProperties(temp, bo);
				return bo;
			}).filter(item -> item != null).collect(Collectors.toList());
			pageResult.setRows(responseList);
			pageResult.setTotal(count);
		} catch (Exception e) {
			log.error("查询列表异常",e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION);
		}
		return RestResult.success(pageResult);
	}

	/**
	 * CMS_PAGE 查询列表（不分页）
	 * @param  request 前端请求参数
	 */
	@PostMapping("/listAll")
	@ApiOperation(value = "不分页查询cmsPage列表")
	@ResponseBody
	public RestResult<List<CmsPageResponse>>  listCmsPageAllRecord(@RequestBody CmsPageRequest request) throws Throwable {
		//分页处理
		CmsPageRequest cmsPageRequest = new CmsPageRequest();
		CmsPage cmsPage = new CmsPage();
		BeanUtils.copyProperties(request, cmsPage);
		List<CmsPage> list = cmsPageService.listCmsPageAllRecord(cmsPage);
		List<CmsPageResponse> responseList = list.stream().map(temp -> {
			CmsPageResponse bo = new CmsPageResponse();
			BeanUtils.copyProperties(temp, bo);
			return bo;
		}).filter(item -> item != null).collect(Collectors.toList());
		return RestResult.success(responseList);
	}

	/**
	 * 单表查询详情信息
	 * @param request 查询详情请求参数
	 * @return CmsPageResponse 查询详情响应参数
	 * author Taozhouchuan
	 * @date 2020-3-11 20:54:04
	 */
	@PostMapping("/viewCmsPage")
	@ApiOperation(value = "查询cmsPage详情")
	@ResponseBody
	public RestResult<CmsPageResponse> getCmsPageDetail(@Validated @RequestBody CmsPageRequest request) {
		log.info("查询详情请求参数入参，{}", JSONObject.toJSONString(request));
		if (request!=null && request.getId()!=null) {

			CmsPage cmsPage = new CmsPage();
			BeanUtils.copyProperties(request, cmsPage);
			CmsPage result = cmsPageService.getCmsPage(cmsPage);
			log.info("查询详情请求参数出参，{}", JSONObject.toJSONString(result));
			if (result == null) {
				return RestResult.error("9999", "记录不存在");
			}
			CmsPageResponse bo = new CmsPageResponse();
			BeanUtils.copyProperties(result, bo);
			return RestResult.success(bo);
		}
		log.info("查询详情请求结束");
		return RestResult.success(new CmsPageResponse());
	}
	/**
	 * 新增或修改cmsPage记录
	 * @param request 新增或修改请求参数
	 * @return CmsPageResponse 新增或修改响应参数
	 * author Taozhouchuan
	 * @date 2020-3-11 20:54:04
	 */
	@ApiOperation(value = "保存或更新cmsPage")
	@PostMapping("/saveOrUpdateCmsPage")
	@ResponseBody
	public RestResult<Long> saveOrUpdateCmsPage(@Validated @RequestBody CmsPageRequest request) throws Throwable {
		//分页处理
		CmsPage cmsPage = new CmsPage();
		BeanUtils.copyProperties(request, cmsPage);
		long flag =   cmsPageService.saveOrUpdateCmsPage(cmsPage);
		if(flag>0){
			return RestResult.success(flag);
		}else{
			return RestResult.error("9999", "新增或修改异常");
		}
	}
	/**
	 * 修改cmsPage记录
	 * @param request 修改请求参数
	 * @return CmsPageResponse 修改响应参数
	 * author Taozhouchuan
	 * @date 2020-3-11 20:54:04
	 */
	@ApiOperation(value = "修改cmsPage记录")
	@PostMapping("/updateCmsPage")
	@ResponseBody
	public RestResult<Long> updateCmsPage(@RequestBody CmsPageRequest request) throws Throwable {
		//分页处理
		CmsPage cmsPage = new CmsPage();
		BeanUtils.copyProperties(request, cmsPage);
		long flag = cmsPageService.updateCmsPage(cmsPage);
		if(flag>0){
			return RestResult.success(flag);
		}else{
			return RestResult.error("9999", "修改异常");
		}
	}
	/**
	 * 新增cmsPage记录
	 * @param request 新增请求参数
	 * @return CmsPageResponse 新增响应参数
	 * author Taozhouchuan
	 * @date 2020-3-11 20:54:04
	 */
	@ApiOperation(value = "新增cmsPage记录")
	@PostMapping("/addCmsPage")
	@ResponseBody
	public RestResult<Long> addCmsPage(@RequestBody CmsPageRequest request) throws Throwable {
		//分页处理
		CmsPage cmsPage = new CmsPage();

		BeanUtils.copyProperties(request, cmsPage);
		cmsPage.setStartDate(new Date());
		cmsPage.setEndDate(new Date());
		cmsPage.setUpdateTime(new Date());
		cmsPage.setStatus(CmsPageStatusEnums.DRAFT_STATUS.getName());//草稿;
		//默认为平台首页
		cmsPage.setPageType(request.getPageType() == null ? CmsPageTypeEnums.PLATFORM_HOME_PAGE.getType() : request.getPageType());
		if (cmsPage.getPageType().equals(CmsPageTypeEnums.PLATFORM_MARKET_PAGE.getType())){
			cmsPage.setTitle("测试营销页");
		}else {
			cmsPage.setTitle("测试首页");
		}
		cmsPage.setDeleteFlag(0);
		cmsPage.setDeptId(request.getAdminOperate().getDeptId() == null ? null : request.getAdminOperate().getDeptId());
		cmsPage.setDeptType(request.getAdminOperate().getDeptType() == null ? DeptTypeEnums.OPERATION_PLATFORM.getCode() : request.getAdminOperate().getDeptType().getCode());
		long flag = cmsPageService.addCmsPage(cmsPage);
		if(flag>0){
//			List<CmsPage> cmsPages = cmsPageService.listCmsPageAllRecord(cmsPage);
//			if (cmsPage!=null && cmsPages.size()==1){
				return RestResult.success(cmsPage.getId());
//			}else{
//				RestResult.error("9999", "获取刚刚新增的记录id异常");
//			}

		}
			return RestResult.error("9999", "新增异常");
	}
	/**
	 * 逻辑删除cmsPage记录
	 * @param request cmsPage 逻辑删除请求参数
	 * @return CmsPageResponse 逻辑删除响应参数
	 * author Taozhouchuan
	 * @date 2020-3-11 20:54:04
	 */
	@ApiOperation(value = "逻辑删除cmsPage记录")
	@PostMapping("/deleteCmsPageLogically")
	@ResponseBody
	public RestResult<Long> deleteCmsPageLogically(@RequestBody CmsPageRequest request) throws Throwable {
		//分页处理
		CmsPage cmsPage = new CmsPage();
		BeanUtils.copyProperties(request, cmsPage);
		long flag =  cmsPageService.deleteCmsPageLogically(cmsPage);
		if(flag>0){
			return RestResult.success(flag);
		}else{
			return RestResult.error("9999", "逻辑删除异常");
		}
	}
}
